package com.veo.dao;

import com.veo.domain.Permission;
import com.veo.domain.Role;
import org.apache.ibatis.annotations.*;


import java.util.List;

public interface RolesDao {

    //根据id查角色
    @Select("select * from role where id in (select roleId from users_role where userId=#{userId})")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "roleName",property = "roleName"),
            @Result(column = "roleDesc",property = "roleDesc"),
            @Result(column = "id",property = "permissions",javaType = List.class,many = @Many(select = "com.veo.dao.PermissionsDao.findPermissionById"))
    })
    List<Role> findRoleById(String userId);

    //根据角色id查找用户和权限
    @Select("select * from role where id=#{roleId}")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "roleName",property = "roleName"),
            @Result(column = "roleDesc",property = "roleDesc"),
            @Result(column = "id",property = "permissions",javaType = List.class,many = @Many(select = "com.veo.dao.PermissionsDao.findPermissionById")),
            @Result(column = "id",property = "users",javaType = List.class,many = @Many(select = "com.veo.dao.UserDao.findUserByRoleId")),
    })
    Role findRoleAndPermissions(String roleId);

    //查询所有角色
    //@Select("select * from role")
    @Select("<script>" + "select * from role "+"<where>"+
            "<if test=\"searcherName!= null and searcherName!=''\"> roleName like concat(#{searcherName},'%')</if>"+
            "</where>"+
            "</script>")
    List<Role> findAllRole(@Param("searcherName") String searcherName);

    //添加角色
    @Insert("insert into role(id,roleName,roleDesc) values(#{id},#{roleName},#{roleDesc})")
    int addRole(Role role);

    //根据id查角色
    @Select("select * from role where id=#{roleId}")
    Role findById(String roleId);

    //为角色查找可用的权限
    @Select("select * from permission where id not in (select permissionId from role_permission where roleId=#{roleId})")
    List<Permission> findPermissionToRole(String roleId);

    //为用户添加权限
    @Insert("insert into role_permission(roleId,permissionId) values(#{roleId},#{permissionId})")
    int addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId);

    //删除角色
    @Delete("delete from role_permission where roleId=#{id}")
    int deleteRolePermissionId(String id);
    @Delete("delete from role where id=#{id}")
    int deleteRoleById(String id);
}
